package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.constants.AdminConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    /**
     * 根据ap_user_id查询当前用户
     *
     * @param id
     * @return
     */
    @Override
    public WmUser findByApUserId(Integer id) {
        return this.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getApUserId, id));
    }


    /**
     * 根据登录名查询当前用户
     *
     * @param name
     * @return
     */
    @Override
    public WmUser findByName(String name) {
        return this.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, name));
    }

    /**
     * 自媒体登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(WmUserDto dto) {
        // 参数校验 dto name password
        if (dto == null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 根据name查找user 判空
        WmUser wmUser = this.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        if (wmUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 判断status是否可用
        if (!wmUser.getStatus().equals(AdminConstants.ADUSER_NORMAL_STATUS)) {
            CustException.cust(AppHttpCodeEnum.ADMIN_USER_NOT_NORMAL);
        }
        // 密码比对
        String dbPwd = wmUser.getPassword();
        String digestPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + wmUser.getSalt()).getBytes());
        if (!digestPwd.equals(dbPwd)) {
            CustException.cust(AppHttpCodeEnum.ADMIN_PASSWORD_ERROR);
        }
        // 更新登录时间
        wmUser.setLoginTime(new Date());
        this.updateById(wmUser);
        // 返回前端token  jwt(id)  user
        HashMap<String, Object> map = new HashMap<>();
        wmUser.setPassword(null);
        wmUser.setSalt(null);
        wmUser.setPhone(null);
        wmUser.setStatus(null);
        map.put("user", wmUser);

        String token = AppJwtUtil.getToken(wmUser.getId().longValue());
        map.put("token", token);
        return ResponseResult.okResult(map);
    }
}
